import 'dart:async';
import 'dart:convert';

import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_reader/dao/login_data_manager.dart';
import 'package:flutter_reader/dao/me_data_manager.dart';
import 'package:flutter_reader/model/home/HotModel.dart';
import 'package:flutter_reader/pages/read_book/book_introduction.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_reader/tools/globals.dart' as globals;


/// 墨水瓶（`InkWell`）可用时使用的字体样式。
final TextStyle _availableStyle = TextStyle(
  fontSize: 16.0,
  color: Color(0xffe53935),
);

/// 墨水瓶（`InkWell`）不可用时使用的样式。
final TextStyle _unavailableStyle = TextStyle(
  fontSize: 16.0,
  color: Colors.black26,
);

class BindPage extends StatefulWidget {

  /// 倒计时的秒数，默认60秒。
  final int countdown;
  /// 用户点击时的回调函数。
  final Function onTapCallback;
  /// 是否可以获取验证码，默认为`false`。
  final bool available;

  final bool hasMobile;

  BindPage({this.hasMobile, this.countdown : 60, this.onTapCallback, this.available: true});

  @override
  _BindPageState createState() {
    return _BindPageState();
  }
}

bool isPhone(String input) {
  RegExp mobile = new RegExp(r"1[0-9]\d{9}$");
  return mobile.hasMatch(input);
}

class _BindPageState extends State<BindPage> {

  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();


  /// 倒计时的计时器。
  Timer _timer;
  /// 当前倒计时的秒数。
  int _seconds;
  /// 当前墨水瓶（`InkWell`）的字体样式。
  TextStyle inkWellStyle = _availableStyle;
  /// 当前墨水瓶（`InkWell`）的文本。
  String _verifyStr = '获取验证码';

   String _hasLogin;
  @override
  void initState() {
    checkLogin();
    _seconds = widget.countdown;
    // initPlatformState();
    super.initState();
  }

  /// 启动倒计时的计时器。
  void _startTimer() {
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _timer = Timer.periodic(
        Duration(seconds: 1),
            (timer) {
          if (_seconds == 0) {
            _cancelTimer();
            _seconds = widget.countdown;
            inkWellStyle = _availableStyle;
            setState(() {});
            return;
          }
          _seconds--;
          _verifyStr = '已发送$_seconds'+'s';
          setState(() {});
          if (_seconds == 0) {
            _verifyStr = '重新发送';
          }
        });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }

  @override
  void dispose() {
    _cancelTimer();
    super.dispose();
  }

  ///集成极光推送
  String debugLable = 'Unknown';
  // final JPush jpush = new JPush();

  // Future<void> initPlatformState() async {
  //   String platformVersion;
  //   try {
  //     jpush.addEventHandler(
  //       onOpenNotification: (Map<String, dynamic> message) async {
  //         print('通知栏打开');
  //         print("flutter onOpenNotification: $message");
  //         print("${message["extras"]}");
  //         print("${message["extras"]["cn.jpush.android.EXTRA"]}");
  //         Map aa = json.decode(message["extras"]["cn.jpush.android.EXTRA"]);
  //         print("${aa["bookID"]}");
  //         Navigator.push(context, MaterialPageRoute(
  //             builder: (context) => BookInfoPage(bookId: aa["bookID"],channel: "1",)
  //         ));
  //       },
  //     );
  //   } on PlatformException {
  //     platformVersion = 'Failed to get platform version.';
  //   }
  // }

  checkLogin() async{
    SharedPreferences preferences = await SharedPreferences.getInstance();
    final hasLogin = preferences.getString('login');
    print(hasLogin);
    setState(() {
      if(hasLogin == null)
        {
          _hasLogin = 'false';
        }
      else
        {
          if(hasLogin == 'true')
            {
              _hasLogin = 'true';
            }
          else
            {
              _hasLogin = 'false';
            }
        }
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      resizeToAvoidBottomPadding: true,
      appBar: AppBar(
        title: Text(
          '绑定手机号'
        ),
      ),
      body: _hasLogin == 'false' ?
      Container(
        width: ScreenUtil().setWidth(1045),
        height: ScreenUtil().setHeight(300),
        margin: EdgeInsets.only(top: ScreenUtil().setHeight(800),
            left: ScreenUtil().setWidth(40),
            right: ScreenUtil().setWidth(40)),
        decoration: BoxDecoration(
          boxShadow: [
            BoxShadow(
              color: Colors.black38,
              blurRadius: 10.0,
              offset: Offset(3.0, 3.0),),
          ],
          gradient: LinearGradient(
            colors: <Color>[
              Color(0xffb31217),
              Color(0xffe52d27)
            ],
          ),
          borderRadius: BorderRadius.all(Radius.circular(10)),
        ),
        child: Center(
          child: Text('-  请先使用手机号快速登录  -',
            style: TextStyle(
                fontSize: ScreenUtil().setSp(50),
                color: Colors.white
            ),),
        ),
      ) : widget.hasMobile == true ? Container(
        width: ScreenUtil().setWidth(1045),
        height: ScreenUtil().setHeight(300),
        margin: EdgeInsets.only(top: ScreenUtil().setHeight(800),
            left: ScreenUtil().setWidth(40),
            right: ScreenUtil().setWidth(40)),
        decoration: BoxDecoration(
          boxShadow: [
            BoxShadow(
              color: Colors.black38,
              blurRadius: 10.0,
              offset: Offset(3.0, 3.0),),
          ],
          gradient: LinearGradient(
            colors: <Color>[
              Color(0xffb31217),
              Color(0xffe52d27)
            ],
          ),
          borderRadius: BorderRadius.all(Radius.circular(10)),
        ),
        child: Center(
          child: Text('-  您已成功绑定手机号  -',
            style: TextStyle(
                fontSize: ScreenUtil().setSp(50),
                color: Colors.white
            ),),
        ),
      ) : SingleChildScrollView(
          reverse: true,
          child: Column(
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(top: ScreenUtil().setHeight(200)),
                child: Center(
                    child: Image(
                      color: Color(0xffe53935),
                      width: ScreenUtil().setWidth(150),
                      image: AssetImage('images/fl_readBook.png'),
                    )
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: ScreenUtil().setWidth(20),top: ScreenUtil().setHeight(300)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      width: ScreenUtil().setWidth(900),
                      child: Text('手机号码',
                        style: TextStyle(
                          fontWeight: FontWeight.w500,
                          fontSize: ScreenUtil().setSp(50),
                          color: Color(0xffe53935),
                        ),),
                    ),
                    Container(
                      width: ScreenUtil().setWidth(900),
                      child: TextField(
                        controller: _phoneController,
                        decoration: InputDecoration(
                          hintText: '请输入手机号',
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: ScreenUtil().setHeight(100)),
                      width: ScreenUtil().setWidth(900),
                      child: Text('验证码',
                        style: TextStyle(
                          fontWeight: FontWeight.w500,
                          fontSize: ScreenUtil().setSp(50),
                          color: Color(0xffe53935),
                        ),),
                    ),
                    Container(
                      width: ScreenUtil().setWidth(900),
                      child: Stack(
                        children: <Widget>[
                          Container(
                            child: TextField(
                              controller: _codeController,
                              decoration: InputDecoration(
                                hintText: '短信验证码',
                              ),
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: ScreenUtil().setHeight(40), left: ScreenUtil().setWidth(600)),
                            child: widget.available ?
                            InkWell(
                              child: Text(
                                '  $_verifyStr  ',
                                style: inkWellStyle,
                              ),
                              onTap: (_seconds == widget.countdown) ? () {
                                print('点击');
                                if(isPhone(_phoneController.text))
                                {
                                  _startTimer();
                                  MeDao.sendCode(int.parse(_phoneController.text)).then((value){
                                    print(value['success']);
                                    print(value['data']);
                                  });
                                  inkWellStyle = _unavailableStyle;
                                  _verifyStr = '$_seconds'+'s后';
                                  setState(() {});
                                }
                                else
                                {
                                  toast('请输入正确的手机号');
                                }
                              } : (){
                                ///倒计时未结束
                                print('${_seconds}-------${widget.countdown}');
                              },
                            )
                                : InkWell(
                              child: Text(
                                '  获取验证码  ',
                                style: _unavailableStyle,
                              ),
                            ),
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: ScreenUtil().setHeight(300)),
                child: SizedBox(
                  width: ScreenUtil().setWidth(1000),
                  height: ScreenUtil().setHeight(150),
                  child: RaisedButton(
                    shape: RoundedRectangleBorder(
                        borderRadius: new BorderRadius.circular(30),
                        side: BorderSide(color: Colors.red)
                    ),
                    onPressed: (){
                      MeDao.bindPhone(int.parse(_phoneController.text), int.parse(_codeController.text)).then((value){
                        print(value);
                        print(value['success']);
                        if(value['success'] == true)
                          {
                            AwesomeDialog(
                              context: context,
                              animType: AnimType.SCALE,
                              dialogType: DialogType.SUCCES,
                              btnOkText: "好的",
                              desc: "您已成功绑定手机号",
                              tittle: "绑定成功",
                              btnOkOnPress: () {
                                Navigator.of(context).popUntil((route) => route.isFirst);
                              },
                            ).show();
                          }
                        else
                          {
                            toast('绑定失败');
                          }
                      });
                    },
                    color: Color(0xffe53935),
                    child: Text('绑定手机号',
                      style: TextStyle(color: Colors.white,
                          fontSize: ScreenUtil().setSp(55)),),
                  ),
                ),
              ),
            ],
          )
      ),
    );
  }
}